package org.jsrml.core.supplier.service;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.jsrml.common.persistence.BaseDao;
import org.jsrml.core.supplier.command.SaveSupplyBankCo;
import org.jsrml.core.supplier.entity.SupplyBank;
import org.jsrml.core.supplier.entity.Vendor;
import org.jsrml.core.supplier.exception.SupplierException;
import org.jsrml.core.supplier.qo.SupplyBankQO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 供应商银行信息
 * @author 张剑
 */
@Service
@Transactional
public class SupplyBankService extends BaseDao<SupplyBank, SupplyBankQO>{
	
	@Autowired
	private VendorService vendorService;
	
	public SupplyBank create(SaveSupplyBankCo command) throws SupplierException{
		
		if(StringUtils.isBlank(command.getVendorId())){
			throw new SupplierException(SupplierException.NECESSARY_PARAM_NULL, "供应商id不能为空！");
		}
		
		Vendor vendor = vendorService.get(command.getVendorId());
		if(vendor==null){
			throw new SupplierException(SupplierException.VENDOR_NOT_FOUND, "供应商没有找到！");
		}
		
		SupplyBank supplyBank = new SupplyBank();
		supplyBank.create(command, vendor);
		
		return supplyBank;
	}
	
	public SupplyBank modify(SaveSupplyBankCo command) throws SupplierException{
		
		if(StringUtils.isBlank(command.getSupplyBankId())){
			throw new SupplierException(SupplierException.NECESSARY_PARAM_NULL, "供应商银行id不能为空！");
		}
		
		if(StringUtils.isBlank(command.getVendorId())){
			throw new SupplierException(SupplierException.NECESSARY_PARAM_NULL, "供应商id不能为空！");
		}
		
		Vendor vendor = vendorService.get(command.getVendorId());
		if(vendor==null){
			throw new SupplierException(SupplierException.VENDOR_NOT_FOUND, "供应商没有找到！");
		}
		
		SupplyBank supplyBank = get(command.getSupplyBankId());
		
		if(supplyBank == null){
			throw new SupplierException(SupplierException.VENDOR_NOT_FOUND, "供应商银行没有找到！");
		}
		supplyBank.modify(command, vendor);
		
		return supplyBank;
	}
	
	public void close(String bankId) throws SupplierException{
		if(StringUtils.isBlank(bankId)){
			throw new SupplierException(SupplierException.NECESSARY_PARAM_NULL, "供应商银行id不能为空！");
		}
		
		SupplyBank supplyBank = get(bankId);
		if(supplyBank == null){
			throw new SupplierException(SupplierException.VENDOR_NOT_FOUND, "供应商银行没有找到！");
		}
		supplyBank.close();
	}

	@Override
	protected Criteria buildCriteria(Criteria criteria, SupplyBankQO qo) {
		return criteria;
	}

	@Override
	protected Class<SupplyBank> getEntityClass() {
		return SupplyBank.class;
	}
	
}
